package cn.ddd.linktran.infrastructure.token.gateway;

import cn.ddd.linktran.domain.domainobject.TokenDO;
import cn.ddd.linktran.domain.gateway.TokenGateWay;
import cn.ddd.linktran.infrastructure.token.convertor.TokenConvertor;
import cn.ddd.linktran.infrastructure.token.mapper.AccessTokenMapper;
import cn.ddd.linktran.infrastructure.token.po.AccessToken;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class TokenGatewayIml implements TokenGateWay {

    @Autowired
    private AccessTokenMapper accessTokenMapper;

    @Override
    public void insertToken(TokenDO tokenDO) {
        AccessToken accessToken = TokenConvertor.toPO(tokenDO);
        accessTokenMapper.insert(accessToken);
    }

    @Override
    public TokenDO selectByAppId(String appId) {
        List<AccessToken> accessTokens = accessTokenMapper.selectList(
                Wrappers.<AccessToken>lambdaQuery()
                        .eq(AccessToken::getAppId, appId)
                        .last("limit 1")           // 只取一条，避免多条时 selectOne 抛异常
        );
        return CollectionUtils.isEmpty(accessTokens)?null: TokenConvertor.toDO(accessTokens.get(0));
    }

    @Override
    public TokenDO selectByAppIdAndAppSecret(String appId, String appSecret) {
        List<AccessToken> accessTokens = accessTokenMapper.selectList(
                Wrappers.<AccessToken>lambdaQuery()
                        .eq(AccessToken::getAppId, appId)
                        .eq(AccessToken::getAppSecret, appSecret)
                        .last("limit 1")           // 只取一条，避免多条时 selectOne 抛异常
        );
        return CollectionUtils.isEmpty(accessTokens)?null: TokenConvertor.toDO(accessTokens.get(0));
    }

    @Override
    public void updateByAppIdAndSecret(TokenDO tokenDO) {
        AccessToken accessToken = TokenConvertor.toPO(tokenDO);
        LambdaUpdateWrapper<AccessToken> uw = Wrappers.<AccessToken>lambdaUpdate()
                .eq(AccessToken::getAppId, tokenDO.getAppId())
                .eq(AccessToken::getAppSecret, tokenDO.getAppSecret());
        accessTokenMapper.update(accessToken, uw);
    }
}
